//
//  ST_PeculiarityGroupFooterView.swift
//  btvideo
//
//  Created by mac on 2020/5/30.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
//import ST_CHTCollectionViewWaterfallLayout

/**
 推荐特质group
 */
class ST_PeculiarityGroupFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    
        self.backgroundColor = UIColor.clear
        
        self.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
        }
        
        
        root_view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(25)
        }
        
        root_view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(61)
        }
        NotificationCenter.default.addObserver(self, selector: #selector(thumb_up_noti_handle(noti:)), name: Notification.Name.thumbUp, object: nil)
        
    }
    
    
    @objc fileprivate func thumb_up_noti_handle(noti:Notification){
        
        
//        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController,vc != self.parentViewController else{
            return
        }
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool else{
            return
        }
        
        guard let idx = data_array.firstIndex(where: {$0.group_id.string == id}) else{
            return
        }
            
        let index = Int(idx.uInt)
        
        data_array[safe: index]?.isThumbUp = isThumbUp
        
        if isThumbUp{
            data_array[safe: index]?.thumbUpCount += 1
        }else{
            data_array[safe: index]?.thumbUpCount -= 1
        }
        
        self.collectionView.performBatchUpdates({
            
            self.collectionView.reloadItems(at: [IndexPath.init(row: index, section: 0)])
            
        }) { (f) in
            
        }
            
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
//    MARK:-properties
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "更多此类特质"
        control.textColor = Color.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var root_view:UIView = {
       let control = UIView()
        control.cornerRadius = 30
        control.backgroundColor = .white
        return control
    }()
    
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
       let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = ST_PinterestHomeCellMinimumColumnSpacing
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 10, bottom: 30, right: 10)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_TraitOfOperatCell.self)
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_PeculiarityDetialSupplementView.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.isScrollEnabled = false
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    var modify_height_closure:((CGFloat)->())?
    
    var data_array = [ST_TraitOfOperatCellModel](){
        didSet{
            
            self.collectionView.reloadData {
            
                self.collectionView.layoutIfNeeded()
                self.layout.invalidateLayout()
                
                let figuredSize = self.layout.collectionViewContentSize
                
                print("bug 2542---Size:",figuredSize,"---data_array count:",self.data_array.count)
                
                self.modify_height_closure?(figuredSize.height + 62 + 3)
            }
            
        }
    }
    
//    MARK:
    
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 20
        return control
    }()
    
    fileprivate func pause_video(){
        
        if playerView.frame.width == ScreenWidth{
            return
        }
        playerView.clear_data()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
    }
    
    fileprivate lazy var transition = ST_PairsTransition()
}


//MARK: - UICollectionView Delegate
extension ST_PeculiarityGroupFooterView:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return data_array[safe:indexPath.item]?.size ?? CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_TraitOfOperatCell.self, for: indexPath)
        
        cell.max_content_number_of_lines = 2
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        
        guard let currCell = collectionView.cellForItem(at: indexPath),let objCell = currCell as? ST_PecGroupshareViewRectProtocol,let rootVC = self.parentViewController else{
                    return
                }
                
        let model = data_array[indexPath.row]

            pause_video()
//            1视频 2 图片
            if model.type == .video{

                let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, videoUrl: model.videoUrl, width: model.width, height: model.height)
                
                playerView.setUp(data_array: [currModel])
            }else{
                
                let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, width: model.width, height: model.height)
                
                playerView.setUp(data_array: [currModel])
                
            }
        
        transition.operationView = self.playerView
        
        let rectInScreen = currCell.convert(objCell.picutreframe_in_content_view(), to: nil)
        
        playerView.present_start_rect = rectInScreen
        playerView.present_start_idx = indexPath
        playerView.fromeController = self
     
        let size = CGSize.init(width: model.width, height: model.height)
        
        ST_InteractiveST_PeculiarityGroupViewController.present_interactive_peculiarity_group_controller(accid: model.accid, groupId: model.group_id.string, peculiarity_id: model.feature_id.string, remark: model.sign, firstPhotoSize: size, transition: transition, presentRootController: rootVC)
    }
    
}

extension ST_PeculiarityGroupFooterView:ST_PairsTransitionProtocol{
    
    func present_start_cell()->UICollectionViewCell?{
        
        guard let idx = playerView.present_start_idx  else {
            return nil
        }
        
        return self.collectionView.cellForItem(at: idx)
        
    }
    
}


